package mp

import (
	"duoke/service"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"duoke/utils/request"
	"duoke/utils/response"
	"github.com/gin-gonic/gin"
	"time"
)

var Hexiao = new(hexiaoCtl)

type hexiaoCtl struct{}

func (ctl *hexiaoCtl) Index(c *gin.Context) {
	userR, _ := service.Request.User(c)
	req := request.JsonMap(c)
	if req["orderId"] == nil || req["orderId"] == "" {
		response.Error(c, "订单ID缺失", nil)
		return
	}
	orderId := gconv.Int(req["orderId"])
	if req["goodsId"] == nil || req["goodsId"] == "" {
		response.Error(c, "商品ID缺失", nil)
		return
	}
	goodsId := gconv.Int(req["goodsId"])
	user, err := service.GoodsUser.GetByGoodsUserId(c, goodsId, userR.Id, "")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if user.Id == 0 {
		response.Error(c, "当前用户缺失", nil)
		return
	}
	if user.IsVerifier != 1 {
		response.Error(c, "您不是核销员", nil)
		return
	}
	order, err := service.Order.GetById(c, orderId, "")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if order.Id == 0 || order == nil {
		response.Error(c, "订单不存在", nil)
		return
	}
	if order.HxState != 0 {
		response.Error(c, "该订单已核销过，请勿重复核销", nil)
		return
	}
	if req["getInfo"] != nil && gconv.Int(req["getInfo"]) == 1 {
		response.Success(c, "", order)
		return
	}
	order.HxState = 1
	order.HxTime = gconv.Int(time.Now().Unix())
	order.VerifierId = user.UserId
	affected, err := orm.Db.ID(order.Id).Update(order)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if affected == 0 {
		response.Error(c, "修改核销记录失败", nil)
		return
	}
	response.Success(c, "核销成功", nil)
}

func (ctl *hexiaoCtl) List(c *gin.Context) {
	userR, _ := service.Request.User(c)
	where := "hx_state = 1 AND verifier_id = " + gconv.String(userR.Id)
	list, err := service.Order.List(c, where, 1000, "")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", list)
}
